package com.sinog.biz.service.business.impl;

import com.sinog.biz.BizApplication;
import com.sinog.biz.mapper.havexml.AreaCodeFullMapper;
import com.sinog.biz.mapper.havexml.DepartmentMapper;
import com.sinog.biz.mapper.havexml.PrisonerMainMapper;
import com.sinog.biz.mapper.havexml.SystemCodeMapper;
import com.sinog.biz.mapper.havexml.other.GenerateAccountMapper;
import com.sinog.biz.mapper.havexml.other.UserLoginDetailsMapper;
import com.sinog.biz.service.business.MaintenanceService;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

/**
 * @desc 运维功能实现类
 * @author ybl
 * @date 2022/10/19
 */
@Slf4j
@Service
public class MaintenanceServiceImpl implements MaintenanceService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private SystemCodeMapper systemCodeMapper;
    @Resource
    private UserLoginDetailsMapper userMapper;
    @Resource
    private AreaCodeFullMapper areaCodeFullMapper;
    @Resource
    private PrisonerMainMapper prisonerMainMapper;
    @Resource
    private GenerateAccountMapper generateAccountMapper;
    private JdbcTemplate bujiJdbcTemplate;

    /**
     * 描述
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result generateAccount() {
        String data = "测试";
        Date date = new Date();
        //dd-MMM-yyyy HH:mm:ss:SSS
        SimpleDateFormat formatter = new SimpleDateFormat("ssSSS");
        String dateSuffix =formatter.format(date);
        //data要生成的部门名称前缀
        //固定的用户名前缀，后期抽出去
        String userHead = "maintenance";
        //1 查询出要新增的监狱局、地市司法局、社矫总队，省司法厅最上面的4层     0-监狱局，1-地市司法局，2-社交总队，3-省
        List<Integer> idList = new ArrayList<>(4);
        int shengId = departmentMapper.getThreeId();
        idList.add(0,shengId/100);
        idList.add(1,shengId+100);
        idList.add(2,shengId);
        idList.add(3,shengId);
        //2 处理数据，将要生成的信息存放到map中
        Map<String,String> departmentMap = new HashMap<>(16);
        //本省id
        departmentMap.put("localCode", CodeUrlUtils.getLocalCode());
        //2.1 添加部门id
        //省id
        departmentMap.put("bmShengId",String.valueOf(idList.get(3)));
        //部门监狱局id
        departmentMap.put("bmJyjId",String.valueOf(idList.get(0)));
            //部门监狱id
            departmentMap.put("bmJyId",String.valueOf(idList.get(0)+1));
        //部门地市司法局
        departmentMap.put("bmDsSfjId",String.valueOf(idList.get(1)));
            //部门区县司法局
            departmentMap.put("bmQxFsjId",String.valueOf(idList.get(1)+1) );
                //部门司法所
                departmentMap.put("bmSfsId", departmentMap.get("bmQxFsjId")+"001");
        //部门社矫总队
        departmentMap.put("bmSjzdId", idList.get(2) + "X");
        //部门市社矫机构
        departmentMap.put("bmSSjjgId", (idList.get(2) + 100) + "X");
        //部门区县社矫机构
        departmentMap.put("bmQxSjjgId", (idList.get(2) + 101) + "X");
        //社矫中心
        departmentMap.put("bmSjzxId", (idList.get(2) + 101) + "001X");
        departmentMap.put("localCode",CodeUrlUtils.getLocalCode());
        departmentMap.put("describeHead",data);
        departmentMap.put("describeEnd",dateSuffix);
        //数据库部门创建
        generateAccountMapper.addAutoDepartment(departmentMap);
        //地区创建
        generateAccountMapper.addAutoRegion(departmentMap);
        //存在地区缓存表
        generateAccountMapper.addAreaCodeFull(departmentMap);
        //用户子用户缓存表
        generateAccountMapper.addAutoTbsysUserChildCache(departmentMap);
        //2.2 处理添加账号
        List<String> accountList = new ArrayList<>(16);
        accountList.add(userHead+"_jyj_"+dateSuffix);
        accountList.add(userHead+"_jy_"+dateSuffix);
        accountList.add(userHead+"_dssfj_"+dateSuffix);
        accountList.add(userHead+"_qxsfj_"+dateSuffix);
        accountList.add(userHead+"_sfs_"+dateSuffix);
        accountList.add(userHead+"_szzd_"+dateSuffix);
        accountList.add(userHead+"_ssjjg_"+dateSuffix);
        accountList.add(userHead+"_qxsjjg_"+dateSuffix);
        accountList.add(userHead+"_sjzx_"+dateSuffix);
        accountList.add(userHead+"_ssft_"+dateSuffix);
        //2.3添加账号信息
        generateAccountMapper.addAutoAccount(accountList);
        //2.4添加用户信息
        Map<String,String> authUserMap = new LinkedHashMap<>(  16);
        authUserMap.put("jyj", userHead+"_jyj_"+dateSuffix);
        authUserMap.put("jy", userHead+"_jy_"+dateSuffix);
        authUserMap.put("dssfj", userHead+"_dssfj_"+dateSuffix);
        authUserMap.put("qxsfj", userHead+"_qxsfj_"+dateSuffix);
        authUserMap.put("sfs", userHead+"_sfs_"+dateSuffix);
        authUserMap.put("szzd", userHead+"_szzd_"+dateSuffix);
        authUserMap.put("ssjjg", userHead+"_ssjjg_"+dateSuffix);
        authUserMap.put("qxsjjg", userHead+"_qxsjjg_"+dateSuffix);
        authUserMap.put("sjzx", userHead+"_sjzx_"+dateSuffix);
        authUserMap.put("ssft", userHead+"_ssft_"+dateSuffix);
        generateAccountMapper.addTbsysUserAuto(authUserMap, departmentMap);
        //设置时间
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dateTwo =formatter1.format(date);
        //都成功以后，放入redis
        stringRedisTemplate.opsForHash().putAll("maintenance:"+dateTwo, authUserMap);
        return Result.success("新增成功");
    }

    @Override
    public String selectAccountAll() {
        Set<String> keys = stringRedisTemplate.keys("maintenance*");
        TreeSet<String> treeSetKeys = new TreeSet<>(((o1,o2)->o1.compareTo(o2)));
        treeSetKeys.addAll(keys);
        treeSetKeys = (TreeSet<String>)treeSetKeys.descendingSet();
        List<Map<String,Object>> mapList = new ArrayList<>(16);
        for(Object item:treeSetKeys){
            Map<String, Object> map = new HashMap<>(16);
            map.put("serialNumber", item);
            mapList.add(map);
        }
        return JsonUtil.toText(mapList.size(),mapList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result delAutoAccount(String serialNumber) {
        //拿到所有的罪犯号
        String suffix = "%"+serialNumber.substring(serialNumber.length()-5);
        List<String> list = prisonerMainMapper.getAutoAccountPnum("maintenance",suffix);
        for(String item:list){
            deleteByPriNum(item);
        }
        //删除地区tbsys_code，area_code_full
        generateAccountMapper.delAutoRegion(suffix);
        generateAccountMapper.delAreaCodeFull(suffix);
        //删除用户子用户缓存表
        generateAccountMapper.delAutoTbsysUserChildCache(suffix);
        //删除部门tbsys_department
        generateAccountMapper.delAutoDepartment(suffix);
        //删除用户信息tbsys_user
        generateAccountMapper.delTbsysUserAuto(suffix);
        //删除账号auth_user
        generateAccountMapper.delAutoAccount(suffix);
        //删除redis
        stringRedisTemplate.delete(serialNumber);
        return Result.success("删除成功");
    }

    @Override
    public Map<Object,Object> getAutoAccount(String serialNumber) {
        //从Redis获取数据
        Map<Object,Object> entries = stringRedisTemplate.opsForHash().entries(serialNumber);
        return entries;
    }

    /**
     * 删除产生的操作记录，后续把这个换到下面
     * @param priNum 犯罪编号
     */
    private void deleteByPriNum(String priNum){
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("jdbcTemplate");
        String anZhiDeleteSql = "delete from ab_anzhi where pri_num='" + priNum + "'";
        String bangFuDeleteSql = "delete from ab_bangfu where pri_num='" + priNum + "'";
        String jianDingDeleteSql = "delete from ab_cun_jianding where pri_num='" + priNum + "'";
        String genZongBjDeleteSql = "delete from ab_genzongbangjiao where pri_num='" + priNum + "'";
        String jiuZhuDeleteSql = "delete from ab_jiu where pri_num='" + priNum + "'";
        String lieGuanDeleteSql = "delete from ab_lieguan where pri_num='" + priNum + "'";
        String avDeleteSql = "delete from ab_mv where pri_num='" + priNum + "'";
        String paiChaDeleteSql = "delete from ab_paicha where pri_num='" + priNum + "'";
        String abPrisonersDeleteSql = "delete from ab_prisoners where pri_num='" + priNum + "'";
        String abPrisonersJcDeleteSql = "delete from ab_prisoners_jcab where pri_num='" + priNum + "'";
        String shJzDeleteSql = "delete from ab_shehuijiuzhu where pri_num='" + priNum + "'";
        String tuoGuanDeleteSql = "delete from ab_tuoguan where pri_num='" + priNum + "'";
        String xiaoZuDeleteSql = "delete from ab_xiaozu where pri_num='" + priNum + "'";
        String zouFangDeleteSql = "delete from ab_zoufang where pri_num='" + priNum + "'";
        String hnInterfaceOppositeDeleteSql = "delete from hn_interface_opposite where pri_num='" + priNum + "'";
        String hnInterfaceOppositeLogDeleteSql = "delete from hn_interface_opposite_log where pri_num='" + priNum + "'";
        String mainExceltempDeleteSql = "delete from main_exceltemp where pri_num='" + priNum + "'";
        String prisaveTempDeleteSql = "delete from prisave_temp where pri_num='" + priNum + "'";
        String prisonerCjpgDeleteSql = "delete from prisoner_cjpg where pri_num='" + priNum + "'";
        String prisonerFxDeleteSql = "delete from prisoner_fx where pri_num='" + priNum + "'";
        String prisonerHcDeleteSql = "delete from prisoner_hc where pri_num='" + priNum + "'";
        String prisonerMainDeleteSql = "delete from prisoner_main where pri_num='" + priNum + "'";
        String prisonerSrDeleteSql = "delete from prisoner_sr where pri_num='" + priNum + "'";
        String prisonerTransferDeleteSql = "delete from prisoner_transfer where pri_num='" + priNum + "'";
        String prisonerTsDeleteSql = "delete from prisoner_ts where pri_num='" + priNum + "'";
        String prisonerZnDeleteSql = "delete from prisoner_zn where pri_num='" + priNum + "'";
        String prisonerZzDeleteSql = "delete from prisoner_zz where pri_num='" + priNum + "'";
        String prisonersJxjsDeleteSql = "delete from prisoners_jxjs where pri_num='" + priNum + "'";
        String prisonersZyjnDeleteSql = "delete from prisoners_zyjn where pri_num='" + priNum + "'";
        String srExceltempDeleteSql = "delete from sr_exceltemp where pri_num='" + priNum + "'";
        String uploadAppendixFileDeleteSql = "delete from upload_appendix_file where pri_num='" + priNum + "'";
        String xtjcKsywxtDeleteSql = "delete from xtjc_ksywxt where pri_num='" + priNum + "'";
        String znExceltempDeleteSql = "delete from zn_exceltemp where pri_num='" + priNum + "'";
        String prisonerXjxxDeleteSql = "delete from prisoner_xjxx where pri_num='" + priNum + "'";
        bujiJdbcTemplate.update(anZhiDeleteSql);
        bujiJdbcTemplate.update(bangFuDeleteSql);
        bujiJdbcTemplate.update(jianDingDeleteSql);
        bujiJdbcTemplate.update(genZongBjDeleteSql);
        bujiJdbcTemplate.update(jiuZhuDeleteSql);
        bujiJdbcTemplate.update(lieGuanDeleteSql);
        bujiJdbcTemplate.update(avDeleteSql);
        bujiJdbcTemplate.update(paiChaDeleteSql);
        bujiJdbcTemplate.update(abPrisonersDeleteSql);
        bujiJdbcTemplate.update(abPrisonersJcDeleteSql);
        bujiJdbcTemplate.update(shJzDeleteSql);
        bujiJdbcTemplate.update(tuoGuanDeleteSql);
        bujiJdbcTemplate.update(xiaoZuDeleteSql);
        bujiJdbcTemplate.update(zouFangDeleteSql);
        bujiJdbcTemplate.update(hnInterfaceOppositeDeleteSql);
        bujiJdbcTemplate.update(hnInterfaceOppositeLogDeleteSql);
        bujiJdbcTemplate.update(mainExceltempDeleteSql);
        bujiJdbcTemplate.update(prisaveTempDeleteSql);
        bujiJdbcTemplate.update(prisonerCjpgDeleteSql);
        bujiJdbcTemplate.update(prisonerFxDeleteSql);
        bujiJdbcTemplate.update(prisonerHcDeleteSql);
        bujiJdbcTemplate.update(prisonerMainDeleteSql);
        bujiJdbcTemplate.update(prisonerSrDeleteSql);
        bujiJdbcTemplate.update(prisonerTransferDeleteSql);
        bujiJdbcTemplate.update(prisonerTsDeleteSql);
        bujiJdbcTemplate.update(prisonerZnDeleteSql);
        bujiJdbcTemplate.update(prisonerZzDeleteSql);
        bujiJdbcTemplate.update(prisonersJxjsDeleteSql);
        bujiJdbcTemplate.update(prisonersZyjnDeleteSql);
        bujiJdbcTemplate.update(srExceltempDeleteSql);
        bujiJdbcTemplate.update(uploadAppendixFileDeleteSql);
        bujiJdbcTemplate.update(xtjcKsywxtDeleteSql);
        bujiJdbcTemplate.update(znExceltempDeleteSql);
        bujiJdbcTemplate.update(prisonerXjxxDeleteSql);
    }
}